#include "TrafficControlItem.h"

#include <QFont>
#include <QPen>
#include <QDebug>
#include <qmath.h>
#include "utilities.h"
#include "graphicsutilities.h"
#include "trafficcontrolframe.h"
#include "world.h"

TrafficControlItem::TrafficControlItem(const QString &name)
{
  mIntersection = NULL;
}

void TrafficControlItem::setIntersection(const StreetMap::Intersection *intersection)
{
  if (mIntersection != intersection)
  {
    // Rebuild list of light locations
    mLightGraphics.clear();

    World *w = World::instance();
    StreetMap::RoadList roads  = w->mStreetMap->getRoads(intersection);

    foreach(StreetMap::Road *road, roads)
    {
      StreetMap::Road::Lane::DIRECTION dir = road->getDirection(intersection);
      unsigned int numLanes = road->numLanes(dir);

      for (unsigned int i=0; i<numLanes; i++)
      {
        bool valid = true;
        StreetMap::Road::Lane lane = road->lane(dir, i, valid);
        if (valid)
        {
          QGraphicsPixmapItem *pi(new QGraphicsPixmapItem(QPixmap(":/gfx/solid_red_light.png"),0,this->scene()));
          if (lane.direction == StreetMap::Road::Lane::FROM_FIRST_TO_SECOND)
            pi->setPos(lane.segment.begin());
          else
            pi->setPos(lane.segment.end());
          pi->setZValue(GraphicsUtilities::LAYER_LANELINE);
          pi->scale(0.3, 0.3);
          pi->translate(-pi->pixmap().width()/2, -pi->pixmap().height()/2);
          QString key = road->streetName() + QString::number(i);
          mLightGraphics[key] = pi;
        }
      }
    }
    mIntersection = intersection;
  }
}

void TrafficControlItem::setFrame(TrafficControlFrame* frame)
{
  setIntersection(frame->intersection());

  TrafficControl::ConnectionList cl = frame->state().getConnections();

  for (int i=0; i<cl.size(); i++)
  {
    TrafficControl::Connection *conn = cl.at(i);

    if (conn->from)
    {
      QString key = conn->from->streetName() + QString::number(conn->fromLane);
      QMap<QString, QGraphicsPixmapItem*>::iterator it = mLightGraphics.find(key);

      if (it != mLightGraphics.end())
      {
        QGraphicsPixmapItem *tcgfx = it.value();

        if (tcgfx)
        {
          //TrafficControl::LIGHT_COLOR color = frame->state().lightColor(conn->from, conn->fromLane, conn->to, conn->toLane);
          TrafficControl::LIGHT_COLOR color = frame->state().lightColor();
          switch (color)
          {
          case TrafficControl::LIGHT_GREEN: tcgfx->setPixmap(QPixmap(":/gfx/solid_green_light.png")); break;
          case TrafficControl::LIGHT_YELLOW: tcgfx->setPixmap(QPixmap(":/gfx/solid_yellow_light.png")); break;
          case TrafficControl::LIGHT_RED:
          default: tcgfx->setPixmap(QPixmap(":/gfx/solid_red_light.png")); break;
          }
        }
      }
    }
  }
}

